#!/bin/bash

connects=$@
[ -z "$connects" -a -r connects.lst ] && connects=`cat connects.lst | awk '{print $1}' | sed 's/#.*$//' | sed -n '/^$/!p'`
if [ -z "$connects" ]; then
    echo "connects list is empty. exit"
    exit 1
fi

ssh_to_ssh_key=`cat -s $HOME/.ssh/id_dsa.pub`
ssh2_to_ssh_key=`cat -s $HOME/.ssh2/id_dsa_ssh.pub`
ssh_to_ssh2_key=`cat -s $HOME/.ssh/id_dsa_ssh2.pub`
ssh2_to_ssh2_key=`cat -s $HOME/.ssh2/id_dsa.pub`
#correct for ssh-command
ssh_to_ssh2_key=$(echo "$ssh_to_ssh2_key" | sed 's/\\/\\\\/g' | sed 's/"/\\\"/g' )
ssh2_to_ssh2_key=$(echo "$ssh2_to_ssh2_key" | sed 's/\\/\\\\/g' | sed 's/"/\\\"/g')

for connect in $connects
do
    echo $connect | grep @ >/dev/null
    if [ $? -eq 0 ]; then
	user=`echo $connect | awk -F@ '{print $1}'`
	host=`echo $connect | awk -F@ '{print $2}'`
    else
	user=$LOGNAME
	host=$connect
    fi

    echo $user@$host
    echo "----------------"
    command=" mkdir -p .ssh; \
	      mkdir -p .ssh2; \
	      echo \"$ssh_to_ssh_key\" | grep -v ^$ >> .ssh/authorized_keys; \
	      echo \"$ssh2_to_ssh_key\" | grep -v ^$ >> .ssh/authorized_keys; \
	      echo \"$ssh_to_ssh2_key\" | grep -v ^$ > .ssh2/${HOSTNAME}_${LOGNAME}_ssh.pub; \
	      echo \"$ssh2_to_ssh2_key\" | grep -v ^$ > .ssh2/${HOSTNAME}_${LOGNAME}_ssh2.pub; \
	      [ -z \"$ssh2_to_ssh_key\" ] && ssh-keygen -X -f .ssh2/${HOSTNAME}_${LOGNAME}_ssh2.pub >> .ssh/authorized_keys 2>/dev/null
	      echo \"Key ${HOSTNAME}_${LOGNAME}_ssh.pub\" >> .ssh2/authorization; \
	      echo \"Key ${HOSTNAME}_${LOGNAME}_ssh2.pub\" >> .ssh2/authorization; \
	      cat .ssh/authorized_keys | sort | uniq > .ssh/a.temp; mv .ssh/a.temp .ssh/authorized_keys; \
	      cat .ssh2/authorization | sort | uniq > .ssh2/a.temp; mv .ssh2/a.temp .ssh2/authorization"

    ssh $user@$host "$command"
done

exit 0
